
#include "usart.h"
#include "MQTTPacket.h"
#include "string.h"
#include "OLED_I2C.h"
#include "cmsis_os.h"
//#include "interface.h"
#include "gpio.h"
#include "mqttclient.h"


extern osMessageQId RxQueueHandle;
MQTTString topicString;
uint8_t e;
uint8_t rec;
uint8_t buf2[30];


 int mqtt_connect(char* Username,char* Password, char* ClientID,int keepAlive){

	MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
	
	
	unsigned char buf[100];
	
	int buflen = sizeof(buf);
	int len = 0;
	data.clientID.cstring = ClientID;
	data.keepAliveInterval = keepAlive;
	data.cleansession = 1;
	data.username.cstring = Username;
	data.password.cstring = Password;

	data.willFlag = 1;
	data.will.message.cstring = "device disconnated!";
	data.will.qos = 1;
	data.will.retained = 0;
	data.will.topicName.cstring = "willtopic";
	
	len=MQTTSerialize_connect(buf, buflen, &data);
aa:HAL_UART_Transmit(&huart1,buf,len,100);
	HAL_UART_Receive_IT(&huart1,&rec,1);
	HAL_Delay(500);
	if(e==0){
		goto aa;}else{
	return e;}
}
 
void subscribe(char* topic)
{
	unsigned char buf[30];
	
	int buflen = sizeof(buf);
	topicString.cstring=topic;
	int qos=1;
	int len = 0;
	len = MQTTSerialize_subscribe(buf, buflen, 0, 1, 1, &topicString,&qos );
	HAL_UART_Transmit(&huart1,buf,len,10);
	//HAL_Delay(100);

}

void publish(char* topicName, char* payload,int qos)
{
	unsigned char buf[36];
	topicString.cstring =topicName;
	//int buflen = sizeof(buf);
	int payloadlen=strlen(payload);
	
	int len = 0;
	len = MQTTSerialize_publish(buf, sizeof(buf), 0, qos, 0, 0,topicString , (unsigned char*)payload, payloadlen);
	HAL_UART_Transmit(&huart1,buf,len,10);
	//HAL_Delay(100);
	//HAL_UART_Receive_IT(&huart1,buf2,13);
}



void Ping(void)
{
	uint8_t ping[]={0xC0,0X00};
	HAL_UART_Transmit(&huart1,ping,2,10);
}

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{ 
	if(huart->Instance==USART1)
	{
		//HAL_GPIO_TogglePin(GPIOB,GPIO_PIN_0);
			uint8_t k=0;
			
			switch (rec)
			{
				case 0x30:
					while(rec!=0x0a)
					{
						buf2[k]=rec;
						k++;
						HAL_UART_Receive(&huart1,&rec,1,1);
						if(k==30)break;
					}
					if(k<30&k>10)
					{
						uint8_t dup;
						int qos;
						//uint8_t i;
						uint8_t retained;
						uint16_t msgid;
						int payloadlen;
						uint8_t* payload;
						uint8_t put[]="";
						MQTTString receivedTopic;
						MQTTDeserialize_publish(&dup, &qos, &retained, &msgid, &receivedTopic,&payload, &payloadlen, buf2, k);
						strcpy((char*)put,(const char*)payload);
		
						if(osMessagePut(RxQueueHandle,(uint32_t)put,0)!=osOK){
							publish("topic2","0001",1);
						}
						
							//OLED_ShowStr(24,7,(uint8_t *)qos,1);
					}
					break;
				case 0x20:
					e=1;
					break;
				default :
					break;
		}
			memset(buf2,0,sizeof(buf2));
			HAL_UART_Receive_IT(&huart1,&rec,1);
	}
		
}

 

